import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Layout from '@/layouts/BasicLayout.vue'

Vue.use(Router)

// 配置 NProgress
NProgress.configure({ 
  showSpinner: false,
  minimum: 0.1
})

// 修复路由方法
const originalPush = Router.prototype.push
Router.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => err)
}

const originalReplace = Router.prototype.replace
Router.prototype.replace = function(location) {
  return originalReplace.call(this, location).catch(err => err)
}

// 静态路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/error/404.vue'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'el-icon-s-home' }
      }
    ]
  }
]

// 动态路由
export const asyncRoutes = [
  {
    path: '/system',
    component: Layout,
    redirect: '/system/user',
    meta: { title: '系统管理', icon: 'el-icon-setting' },
    children: [
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/system/user/index.vue'),
        meta: { 
          title: '用户管理',
          permissions: ['system:user:list']
        }
      },
      {
        path: 'role',
        name: 'Role',
        component: () => import('@/views/system/role/index.vue'),
        meta: {
          title: '角色管理',
          permissions: ['system:role:list']
        }
      }
    ]
  },
  // 404 页面必须尾
  { path: '*', redirect: '/404', hidden: true }
]

const router = new Router({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: constantRoutes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const token = localStorage.getItem('token')
  
  // 处理登录相关逻辑
  if (!token && to.path !== '/login') {
    next('/login')
    NProgress.done()
    return
  }
  
  if (token && to.path === '/login') {
    next('/')
    NProgress.done()
    return
  }

  try {
    // 处理动态路由
    if (token && !store.state.permission.addRoutes.length) {
      // 获取并添加动态路由
      const accessRoutes = await store.dispatch('permission/generateRoutes')
      accessRoutes.forEach(route => router.addRoute(route))
      
      // 重新导航到目标路由
      next({ ...to, replace: true })
    } else {
      next()
    }
  } catch (error) {
    console.error('路由错误:', error)
    if (error.name !== 'NavigationCancelled') {
      next('/login')
    }
  }
})

// 全局后置钩子
router.afterEach((to) => {
  document.title = to.meta.title 
    ? `${to.meta.title} - 管理系统`
    : '管理系统'
  NProgress.done()
})

// 全局错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  NProgress.done()
})

export default router
